from google.appengine.ext import webapp, gql
from google.appengine.ext.webapp.util import run_wsgi_app
from models import *
from datetime import *
import string
import util
import logging

import Consts

##
#this file main role is to handle with query requests
class DataBaseQueryHandler(webapp.RequestHandler):

    def get(self): 
        self.response.out.write(''' 
        <html> 
          <body> 
            <form method="post"> 
              <p>Type: <input type="string" name="type" /></p>
              <p>Country: <input type="string" name="country" /></p>
              <p>City: <input type="string" name="city" /></p>
              <p>Street: <input type="string" name="street" /></p>
              <p>Street_num: <input type="text" name="street_num" /></p>
              <p>Days_bitmap: <input type="text" name="days_bitmap" /></p>
              <p>Time: <input type="text" name="time" /></p>
              <p>Time_delta: <input type="text" name="time_delta" /></p> 
              <p><input type="submit" /></p> 
            </form> 
          </body> 
        </html> 
        ''') 
 
    def post(self):
        
        logging.info("Starting query request")
                
        #getting form params
        #default value of type is pub
        query_type = self.request.get("type", "all")
        query_country = self.request.get("country", "all")
        query_city = self.request.get("city", "all")
        query_street = self.request.get("street", "all")
        query_street_num = self.request.get("street_num", "all")
        query_time = self.request.get("time", "all")
        query_time_delta = self.request.get("time_delta", "all")
        query_days_bitmap = self.request.get("days_bitmap", "{0}".format(Consts.ALL_DAYS))

        logging.debug("query type = " + unicode(query_type) + ", query_country = " + unicode(query_country) + ", query_city = " + unicode(query_city) + ", query_street = " + unicode(query_street) + ", query_street_num = " + unicode(query_street_num) + ", query_time = " + unicode(query_time) + ", query_time_delta = " + unicode(query_time_delta) + ", query_days_bitmap = " + unicode(query_days_bitmap))
         
        #generate xml and sending it 
        self.response.headers['Content-Type'] = 'text/xml'

        xml_result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        xml_result += "<root>\n"
        
        #type filter
        type_lst = util.get_type_lst_from_type_btm(query_type)
            
        for query_type_elem in type_lst:
            #query business data base for relevant database
            business_list = Business.all()
            business_list.filter("_deleted ==", 0)
            business_list.filter("business_type =", query_type_elem)
            
            #address filter
            if (query_country != None and query_country != "" and query_country != "all"):
                business_list.filter("country ==", query_country)
            if (query_city != None and query_city != "" and query_city != "all"):
                business_list.filter("city ==", query_city)
            if (query_street != None and query_street != "" and query_street != "all"):
                business_list.filter("street ==", query_street)
            if (query_street_num != "" and query_street_num != "0" and query_street_num != "all"):
                business_list.filter("street_num ==", query_street_num)
            
            for business in business_list:
                deal_list = Deal.all()
                #get relevant deals per business
                deal_list.filter("_deleted == ", 0)
                deal_list.filter("business_item ==", business)
                
                #time filter
                #for all, skip filter    
                relevant_deal_list = list()
                for deal_elem in deal_list:
                    #filter by days_bitmap and time
                    if (util.is_deal_in_datetime(deal_elem, query_days_bitmap, query_time, query_time_delta)):
                        relevant_deal_list.append(deal_elem)
                           
                            
                if (len(relevant_deal_list) != 0):
                    xml_result += "<business>\n"
                    xml_result += "<info>\n"
                    xml_result += unicode(business.to_xml())
                    xml_result += "</info>\n"
                    xml_result += "<deals>\n"
    
                    for item in relevant_deal_list:
                        xml_result += "<deal>\n"
                        
                        xml_result += "<dealinfo>\n"
                        xml_result += unicode(item.to_xml())
                        xml_result += "</dealinfo>\n"
                        
                        #get the relevant comments per deal
                        xml_result += "<comments>\n"
                        comment_list = Comment.all()
                        comment_list.filter("deal_item ==", item)
                        for comment in comment_list:
                            xml_result += unicode(comment.to_xml())
                        xml_result += "</comments>\n"
                        
                        xml_result += "</deal>\n"
                    xml_result += "</deals>\n"
                    xml_result += "</business>\n"
                    
        xml_result += "</root>\n"
        
        logging.debug("xml response:")
        logging.debug(xml_result)
        self.response.out.write(xml_result)
        logging.info("Finish query request")
        
        
class DataBaseQueryUserInfoHandler(webapp.RequestHandler):

    def get(self): 
        self.response.out.write(''' 
        <html> 
          <body> 
            <form method="post"> 
              <p>Email: <input type="string" name="email" /></p>
            </form> 
          </body> 
        </html> 
        ''') 
 
    def post(self):
        
        logging.info("Starting query user info request")
         
        #generate xml and sending it 
        self.response.headers['Content-Type'] = 'text/xml'

        xml_result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        xml_result += "<root>\n"
        
        query_email = self.request.get("email", "")
        if (query_email == None or query_email == ""):
            xml_result += "</root>\n"
            logging.debug("xml response:")
            logging.debug(xml_result)
            self.response.out.write(xml_result)
            logging.info("Finish query request")
        
        logging.debug("query user email = " + unicode(query_email))
        
        #search for existed user
        #user_lst = User.all()
        #user_lst.filter("email ==", query_email)
        #user = user_lst.get()
        
        business_list = Business.all()
        business_list.filter("_deleted ==", 0)
        
        for business in business_list:
                deal_list = Deal.all()
                #get relevant deals per business
                deal_list.filter("_deleted == ", 0)
                deal_list.filter("business_item ==", business)
                deal_list.filter("_source ==", query_email)
                           
                            
                if (deal_list.count(limit = 1) != 0):            
                    xml_result += "<business>\n"
                    xml_result += "<info>\n"
                    xml_result += unicode(business.to_xml())
                    xml_result += "</info>\n"
                    xml_result += "<deals>\n"
    
                    for item in deal_list:
                        xml_result += "<deal>\n"
                        
                        xml_result += "<dealinfo>\n"
                        xml_result += unicode(item.to_xml())
                        xml_result += "</dealinfo>\n"
                        
                        #get the relevant comments per deal
                        xml_result += "<comments>\n"
                        comment_list = Comment.all()
                        comment_list.filter("deal_item ==", item)
                        for comment in comment_list:
                            xml_result += unicode(comment.to_xml())
                        xml_result += "</comments>\n"
                        
                        xml_result += "</deal>\n"
                    xml_result += "</deals>\n"
                    xml_result += "</business>\n"
                    
        xml_result += "</root>\n"
        
        logging.debug("xml response:")
        logging.debug(xml_result)
        self.response.out.write(xml_result)
        logging.info("Finish query request")
        
        
        

            
        #deal_lst = Deal.all()
        
application = webapp.WSGIApplication([('/database/query', DataBaseQueryHandler), ('/database/query/user', DataBaseQueryUserInfoHandler)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
